"""
api服务接口
"""
from fastapi import Body
from services.api_wrap import async_api_wrapper, BaseResponse
from fastapi import UploadFile, File
from audios.audio_asr import AudioAsr
from translate.xiaomi_translate import XiaomiTranslator
from classify.news_topic_classify import TextClassifier
from pathlib import Path
from loguru import logger
import edge_tts
from tts.speakers import EdgeTTS_SPEAKERS
import datetime

topic = TextClassifier()
xiaomi = XiaomiTranslator()
asr = AudioAsr()
uploadFiles = Path(__file__).parent.parent / "uploadFiles"
ttsFiles = Path(__file__).parent.parent / "ttsFiles"


@async_api_wrapper
async def asr_api(
        file: UploadFile = File(...),
        lang: str = Body(description='语言', examples=[
            '中文','泰语', '印度尼西亚语', '越南语', '马来语', '缅甸语', '尼泊尔语', '老挝语', '菲律宾语'])
):

    contents = await file.read()
    audio = uploadFiles / file.filename
    with open(audio, 'wb') as fw:
        fw.write(contents)

    audio_text = asr.recognize(audio, lang)
    logger.info(audio_text)
    return BaseResponse(data={'text': audio_text})


@async_api_wrapper
async def translate_api(
        input_text: str = Body(description='文本', examples=[
            '我和他处在完全不同的社会圈子里。', 
            'เราอยู่ในสังคมที่แตกต่างกันโดยสิ้นเชิง',
            'ມື້ນີ້ ອາກາດ ດີ ຫຼາຍ ອກ ໄປ ທ່ອງທ່ຽວ.'
        ]),
        from_lan: str = Body(description='源语言', examples = [
            '中文','泰语', '印度尼西亚语', '越南语','马来语','缅甸语','尼泊尔语','老挝语','菲律宾语']),
        to_lan: str = Body(description='目标语言', examples = [
            '泰语', '印度尼西亚语', '越南语','马来语','缅甸语','尼泊尔语','老挝语','菲律宾语','中文']),
):
    trans_text = xiaomi.translate(input_text, from_lan, to_lan)
    logger.info(trans_text)
    return BaseResponse(data={'text': trans_text})


@async_api_wrapper
async def tts_api(
        input_text: str = Body(description='文本', examples=[
            '我和他处在完全不同的社会圈子里。',
            'เราอยู่ในสังคมที่แตกต่างกันโดยสิ้นเชิง',
            'ມື້ນີ້ ອາກາດ ດີ ຫຼາຍ ອກ ໄປ ທ່ອງທ່ຽວ.'
        ]),
        lang: str = Body(description='语言', examples=[
            '中文','泰语', '印度尼西亚语', '越南语', '马来语', '缅甸语', '尼泊尔语', '老挝语', '菲律宾语'])
):
    communicate = edge_tts.Communicate(text=input_text,
                                       voice=EdgeTTS_SPEAKERS.get(lang, 'zh-CN-YunyangNeural'),
                                       rate='+0%',
                                       volume='+0%',
                                       pitch='+0Hz')
    current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")
    clip_file = ttsFiles / f'{current_time}.wav'
    communicate.save_sync(clip_file.as_posix())
    relative_path = f'ttsFiles/{clip_file.name}'
    return BaseResponse(data={'path': relative_path})


@async_api_wrapper
async def translate_tts_api(
        input_text: str = Body(description='文本', examples=[
            '我和他处在完全不同的社会圈子里。',
            'เราอยู่ในสังคมที่แตกต่างกันโดยสิ้นเชิง',
            'ມື້ນີ້ ອາກາດ ດີ ຫຼາຍ ອກ ໄປ ທ່ອງທ່ຽວ.'
        ]),
        from_lan: str = Body(description='源语言', examples = [
            '中文','泰语', '印度尼西亚语', '越南语','马来语','缅甸语','尼泊尔语','老挝语','菲律宾语']),
        to_lan: str = Body(description='目标语言', examples = [
            '泰语', '印度尼西亚语', '越南语','马来语','缅甸语','尼泊尔语','老挝语','菲律宾语','中文']),
):
    trans_text = xiaomi.translate(input_text, from_lan, to_lan)
    try:
        communicate = edge_tts.Communicate(text=trans_text,
                                           voice=EdgeTTS_SPEAKERS.get(to_lan, 'zh-CN-YunyangNeural'),
                                           rate='+0%',
                                           volume='+0%',
                                           pitch='+0Hz')
        current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")
        clip_file = ttsFiles / f'{current_time}.wav'
        communicate.save_sync(clip_file.as_posix())
        relative_path = f'ttsFiles/{clip_file.name}'
    except Exception as e:
        logger.error(e)
        relative_path = None
    result = {
        'trans_text': trans_text,
        'tts_file': relative_path
    }
    return BaseResponse(data=result)


@async_api_wrapper
async def classify_api(
        texts: str = Body(description='文本'),
        lang: str = Body(description='语言', examples=[
            '中文','泰语', '印度尼西亚语', '越南语', '马来语', '缅甸语', '尼泊尔语', '老挝语', '菲律宾语'])
):
    class_names = topic.predict(texts)
    logger.info(class_names)
    return BaseResponse(data={'class': class_names})